package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.SkuImagesEntity;
import com.atguigu.gulimall.product.entity.SpuInfoDescEntity;
import com.atguigu.gulimall.product.feign.SeckillFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.SeckillInfoVo;
import com.atguigu.gulimall.product.vo.SkuItemSaleAttrVo;
import com.atguigu.gulimall.product.vo.SkuItemVo;
import com.atguigu.gulimall.product.vo.SpuItemAttrGroupVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SkuInfoDao;
import com.atguigu.gulimall.product.entity.SkuInfoEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    SeckillFeignService seckillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        /**
         * key: '华为',//检索关键字
             catelogId: 0,
             brandId: 0,
             min: 0,
             max: 0
         */
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and(w -> {
                w.eq("sku_id",key).or().like("sku_name",key);
            });
        }
        String catelogId = (String)params.get("catelogId");
        //默认分类id是0，所以分类id是0时不需要拼接条件
        if(!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }
        String brandId = (String)params.get("brandId");
        //默认品牌id是0，所以品牌id是0时不需要拼接条件
        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        String min = (String)params.get("min");
        if(!StringUtils.isEmpty(min)){
            //小于等于
            wrapper.ge("price",min);
        }
        String max = (String)params.get("max");
        if(!StringUtils.isEmpty(max)){
            //大于等于，默认最大价格是0，所以最大价格是0时不拼接条件
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                if(bigDecimal.compareTo(new BigDecimal("0")) == 1){
                    wrapper.le("price",max);
                }
            }catch (Exception e){
                //有可能前端输入的不是数字，可能会有异常，如果转换异常，不进行处理
            }
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> skuInfoEntityList = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return skuInfoEntityList;
    }

    /**
     * 封装商品详情页面的Vo
     * 使用异步编排
     * @param skuId
     * @return
     */
    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo itemVo = new SkuItemVo();
        //1、封装sku基本信息  pms_sku_info
        CompletableFuture<SkuInfoEntity> skuFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity skuInfoEntity = this.getById(skuId);
            itemVo.setSkuInfo(skuInfoEntity);
            return skuInfoEntity;
        }, executor);
        //需要获取spuId，故需等待skuId异步执行完毕才能执行，而且要接收参数
        CompletableFuture<Void> saleFuture = skuFuture.thenAcceptAsync((res) -> {
            //3、封装商品销售属性信息，需查询出Spu的所有销售属性  pms_sku_sale_attr_value
            List<SkuItemSaleAttrVo> skuItemSaleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            itemVo.setSaleAttrs(skuItemSaleAttrVos);
        }, executor);
        //需要获取spuId，故需等待skuId异步执行完毕才能执行，而且要接收参数
        CompletableFuture<Void> descFuture = skuFuture.thenAcceptAsync((res) -> {
            //4、封装商品的商品介绍  pms_spu_info_desc
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            itemVo.setDesp(spuInfoDescEntity);
        }, executor);
        //需要获取spuId，故需等待skuId异步执行完毕才能执行，而且要接收参数
        CompletableFuture<Void> attrFuture = skuFuture.thenAcceptAsync((res) -> {
            //5、封装商品的spu规格参数  pms_product_attr_value
            List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuIdAndCatelogId(res.getSpuId(), res.getCatalogId());
            itemVo.setGroupVos(attrGroupVos);
        }, executor);
        //由于与sku的异步编排无关系，这里在开一个异步
        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            //2、封装sku图片信息 pms_sku_images
            List<SkuImagesEntity> imagesEntities = skuImagesService.getImagesBySkuId(skuId);
            itemVo.setImages(imagesEntities);
        }, executor);
        //3、查询商品的秒杀信息
        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            R r = seckillFeignService.getSkuSeckillInfo(skuId);
            if (r.getCode() == 0) {
                SeckillInfoVo seckillInfoVo = r.getData(new TypeReference<SeckillInfoVo>() {
                });
                itemVo.setSeckillInfoVo(seckillInfoVo);
            }
        },executor);

        //阻塞等待上面的异步全部执行完成，异常抛出即可
        CompletableFuture.allOf(saleFuture,descFuture,attrFuture,imageFuture,seckillFuture).get();
        return itemVo;
    }

}